package com.example.socket.utils;

import com.example.socket.core.Session;
import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.regex.Pattern;

/**
 * 获取IP地址的简单工具类
 * @author frank
 */
public abstract class IpUtils {

	/**
	 * 获取会话的IP地址
	 * @param session
	 * @return
	 */
	public static String getIp(Channel session) {
		if (session == null || session.remoteAddress() == null) {
			return "UNKNOWN";
		}
		String ip = session.remoteAddress().toString();
		return StringUtils.substringBetween(ip, "/", ":");
	}
	
	public static String getIp(SocketAddress address){
		return StringUtils.substringBetween(address.toString(), "/", ":");
	}

	/**
	 * 获取会话的IP地址
	 * @param session
	 * @return
	 */
	public static String getIp(Session session) {
		if (session == null || session.getRemoteAddress() == null) {
			return "UNKNOWN";
		}
		String ip = session.getRemoteAddress().toString();
		return StringUtils.substringBetween(ip, "/", ":");
	}

	/*** ip地址正则配置 **/
	public final static Pattern ipPattern = Pattern.compile("^([0-9\\*]+\\.){3}[0-9\\*]+$");

	/**
	 * 验证是否合法的IP
	 */
	public static boolean isValidIp(String ip) {
		return ipPattern.matcher(ip).matches();
	}

	/**
	 * 字符串转换为InetSocketAddress
	 */
	public static InetSocketAddress toInetSocketAddress(String addr) {
		int colonIndex = addr.lastIndexOf(":");
		if (colonIndex > 0) {
			String host = addr.substring(0, colonIndex);
			if (!"*".equals(host)) {
				int port = parsePort(addr.substring(colonIndex + 1));
				return new InetSocketAddress(host, port);
			}
		}

		int port = parsePort(addr.substring(colonIndex + 1));
		return new InetSocketAddress(port);
	}

	private static int parsePort(String s) {
		try {
			return Integer.parseInt(s);
		} catch (NumberFormatException nfe) {
			throw new IllegalArgumentException("Illegal port number: " + s);
		}
	}

	// public static void main(String[] args) {
	// String ip = "192.12.10.*";
	// System.out.println(ipPattern.matcher(ip).matches());
	// }

}
